package cn.itcast.common.utils;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.face.AipFace;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class AipFaceHelper {

	//设置APPID/AK/SK
	private static final String APP_ID = "19808861";
	private static final String API_KEY = "x4dU0KI7O0Z7jMC6bKYHYm97";
	private static final String SECRET_KEY = "m3IL3OPouhBZPGU2qlBbjTehpDVd8ut4";

	private static AipFace client = null;

	static {
		if (client == null) {
			client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
			client.setConnectionTimeoutInMillis(10000);
			client.setSocketTimeoutInMillis(120000);
		}
	}

	/**
	 * 从百度云AI中根据图片查找用户绑定的id
	 */
	public static String faceSearch(String image) {
		HashMap<String, String> options = new HashMap<String, String>();
		options.put("quality_control", "LOW");// 图片质量控制
		options.put("liveness_control", "LOW");//活体检测控制
		options.put("max_user_num", "1"); // 查找后返回的用户数量,返回相似度最高的几个用户

		//调用api完成根据图片识别
		JSONObject res = client.search(image, "BASE64", "002108e29a10451096838d8fd1d374ef", options);

		//解析返回值res
		if(res.has("error_code") && res.getInt("error_code")==0) {
			JSONObject result = res.getJSONObject("result");
			JSONArray userList = result.getJSONArray("user_list");
			if(userList.length()>0) {
				JSONObject user = userList.getJSONObject(0);
				return user.getString("user_id");
			}
		}
		return null;
	}

	public static Map faceAdd(String images, String id){
		HashMap<String, String> options = new HashMap<String, String>();
		options.put("user_info",id);
		options.put("quality_control","LOW");
		options.put("liveness_control","LOW");
		String imageType = "BASE64";
		String groupId = "002108e29a10451096838d8fd1d374ef";
		String userId = id;
		JSONObject jsonObject = client.addUser(images, imageType, groupId, userId, options);
		Map map = JSON.parseObject(jsonObject.toString(), Map.class);
		return map;
	}
}
